<?php


namespace App\Services;



use App\Models\Supplier;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Contracts\JWTSubject;
use App\Utils\Code;
use App\Utils\Regex;

class SupplierService extends BaseService
{

    /**
     * 创建
     * @param array $params
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        if (isset($params['phone']) && $params['phone'] && Supplier::where('phone', $params['phone'])->whereNull('deleted_at')->exists()) {
            throw new \Exception('该手机号已经使用过了', Code::EXIST_REPEAT);
        }
        $userId = \Auth::id();
        return \DB::transaction(function () use ($params, $userId) {
            $model = new Supplier();
            $model->user_id = $userId;
            $model->name = $params['name'];
            if (isset($params['mark']) && $params['mark']) {
                $model->mark = $params['mark'];
            }
            if (isset($params['avatar']) && $params['avatar']) {
                $model->avatar = $params['avatar'];
            }
            if (isset($params['phone']) && $params['phone']) {
                $model->phone = $params['phone'];
            }
            if (isset($params['wechat_name']) && $params['wechat_name']) {
                $model->wechat_name = $params['wechat_name'];
            }
            if (isset($params['wechat_code']) && $params['wechat_code']) {
                $model->wechat_code = $params['wechat_code'];
            }
            if (isset($params['description']) && $params['description']) {
                $model->description = $params['description'];
            }
            if (isset($params['sort']) && $params['sort']) {
                $model->sort = $params['sort'];
            }
            if (isset($params['status'])) {
                $model->status = (int)$params['status'];
            }
            $model->save();
            return $this->show($model->supplier_id);
        });
    }

    /**
     * 验证参数
     * @param array $params
     * @param null $id
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false) {
        $rules = [
            'name' => ['bail', 'required', 'string'],
            'mark' => ['bail', 'nullable', 'string'],
            'avatar' => ['bail', 'nullable', 'string'],
            'phone' => ['bail', 'nullable', 'regex:'.Regex::regex['phone']],
            'wechat_name' => ['bail', 'nullable', 'string'],
            'wechat_code' => ['bail', 'nullable', 'string'],
            'description' => ['bail', 'nullable', 'string'],
            'sort' => ['bail', 'nullable', 'integer'],
            'status' => ['bail', 'integer', 'in:0,1']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    $rule[1] = 'nullable';
                }
            }
        }
        $validator = Validator::make($params, $rules, [
            'status.in' => '场次状态出错'
        ], [
            'name' => '名称',
            'mark' => '助记码',
            'avatar' => '头像',
            'phone' => '手机号',
            'wechat_name' => '微信昵称',
            'wechat_code' => '微信号',
            'description' => '备注',
            'sort' => '排序',
            'status' => '状态'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }

    /**
     * 删除
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function destroy($id = null) {
        $model = Supplier::where('supplier_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该货主不存在或已被删除', Code::EXIST_REPEAT);
        }
        $model->deleted_at = date('Y-m-d H:i:s');
        return $model->save();
    }

    /**
     * 修改
     * @param array $params
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function update(array $params, $id = null) {
        $model = Supplier::where('supplier_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该货主不存在或已被删除', Code::EXIST_REPEAT);
        }
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        if (Supplier::where('phone', $params['phone'])->where('supplier_id', '!=', $id)->whereNull('deleted_at')->exists()) {
            throw new \Exception('该手机号已经使用过了', Code::EXIST_REPEAT);
        }
        return \DB::transaction(function () use ($params, $model) {
            if (isset($params['name']) && $params['name']) {
                $model->name = $params['name'];
            }
            if (key_exists('mark', $params)) {
                $model->mark = $params['mark'];
            }
            if (key_exists('avatar', $params)) {
                $model->avatar = $params['avatar'];
            }
            if (key_exists('phone', $params)) {
                $model->phone = $params['phone'];
            }
            if (key_exists('wechat_name', $params)) {
                $model->wechat_name = $params['wechat_name'];
            }
            if (key_exists('wechat_code', $params)) {
                $model->wechat_code = $params['wechat_code'];
            }
            if (key_exists('description', $params)) {
                $model->description = $params['description'];
            }
            if (isset($params['sort']) && $params['sort']) {
                $model->sort = $params['sort'];
            }
            if (isset($params['status']) && in_array($params['status'], [0,1])) {
                $model->status = (int)$params['status'];
            }
            $model->save();
            return $this->show($model->supplier_id);
        });
    }

    /**
     * 查看详情
     * @param $id
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function show($id = null) {
        $model = Supplier::where('supplier_id', $id)->whereNull('deleted_at')->first();
        if (!$model) {
            throw new \Exception('该货主不存在或已被删除', Code::EXIST_REPEAT);
        }
        return $model;
    }

    /**
     * 查看列表
     * @param array $params
     * @return Builder|\Illuminate\Database\Eloquent\Model|object|JWTSubject|null
     * @throws \Exception
     */
    public function index(array $params) {
        $model = Supplier::whereNull('deleted_at');
        if (isset($params['name']) && $params['name']) {
            $model = $model->where('name', 'like', '%'.$params['name'].'%');
        }
        if (isset($params['mark']) && $params['mark']) {
            $model = $model->where('mark', 'like', '%'.$params['mark'].'%');
        }
        if (isset($params['phone']) && $params['phone']) {
            $model = $model->where('phone', $params['phone']);
        }
        if (isset($params['status'])) {
            $model = $model->where('status', (int)$params['status']);
        }
        if (isset($params['is_list']) && $params['is_list'] == 1) {
            return $model->orderBy('supplier_id', 'desc')->get();
        } else {
            return $model->orderBy('supplier_id', 'desc')
                ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
        }
    }
}
